package com.uitls.utils;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.animation.Interpolator;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.ScrollView;


public class RecyclerViewUtil {
    private static int gridLayoutManagerPosition = 51;
    private static int linearLayoutManagerPosition = 11;

    public static int getRecyclerFirstVisibleItemPosition(RecyclerView recyclerView) {
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        if (layoutManager instanceof LinearLayoutManager) {
            return ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager = ((StaggeredGridLayoutManager) layoutManager);
            return findMin(staggeredGridLayoutManager.findFirstVisibleItemPositions(null));
        }
        return 0;
    }

    private static int findMin(int[] lastPositions) {
        int min = lastPositions[0];
        for (int value : lastPositions) {
            if (value < min) {
                min = value;
            }
        }
        return min;
    }


    /**
     * 可滚动view
     *
     * @param mSmoothToTopView
     */
    public static void smoothScrollToTop(View mSmoothToTopView) {
        if (mSmoothToTopView != null) {
            if (mSmoothToTopView instanceof AbsListView) {
                AbsListView smoothToTopView = (AbsListView) mSmoothToTopView;
                int firstVisiblePosition = smoothToTopView.getFirstVisiblePosition();
                if (firstVisiblePosition < 11) {
                    smoothToTopView.smoothScrollToPosition(0);
                } else {
                    //太多item时加快速度
                    smoothToTopView.setSelection(10);
                    smoothToTopView.smoothScrollToPosition(0);
                }
                smoothToTopView.clearFocus();
            } else if (mSmoothToTopView instanceof RecyclerView) {
                RecyclerView smoothToTopView = (RecyclerView) mSmoothToTopView;
                RecyclerViewUtil.smoothScrollToTop(smoothToTopView);
            } else if (mSmoothToTopView instanceof ScrollView) {
                ScrollView scrollView = ((ScrollView) mSmoothToTopView);
                scrollView.smoothScrollTo(scrollView.getScrollX(), 0);
            } else if (mSmoothToTopView instanceof WebView) {
                ObjectAnimator anim = ObjectAnimator.ofInt(mSmoothToTopView, "scrollY",
                        mSmoothToTopView.getScrollY(), 0);
                anim.setDuration(200).start();
            }
        }
    }

    /**
     * 滚动到顶部
     *
     * @param mRecyclerView
     */
    public static void smoothScrollToTop(RecyclerView mRecyclerView) {
        if (mRecyclerView == null) {
            return;
        }
        int firstVisiblePosition = RecyclerViewUtil.getRecyclerFirstVisibleItemPosition(mRecyclerView);
        RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
        if (layoutManager instanceof GridLayoutManager) {
            if (firstVisiblePosition < gridLayoutManagerPosition) {
                mRecyclerView.smoothScrollToPosition(0);
            } else {
                //太多item时加快速度
                mRecyclerView.scrollToPosition(gridLayoutManagerPosition - 1);
                mRecyclerView.smoothScrollToPosition(0);
            }
        } else if (layoutManager instanceof LinearLayoutManager) {
            if (firstVisiblePosition < linearLayoutManagerPosition) {
                mRecyclerView.smoothScrollToPosition(0);
            } else {
                //太多item时加快速度
                mRecyclerView.scrollToPosition(linearLayoutManagerPosition - 1);
                mRecyclerView.smoothScrollToPosition(0);
            }
        }
        mRecyclerView.clearFocus();
    }

    public static void setLinearLayoutManagerWithoutDivder(Context context, RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    public static void setLinearLayoutManagerHorizontalWithoutDivder(Context context, RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    public static void setLinearLayoutManagerWithDivder(Context context, RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    public static void setGridLayoutManager(Context context, RecyclerView recyclerView, int cow) {
        GridLayoutManager manager = new GridLayoutManager(context, cow);
        recyclerView.setLayoutManager(manager);
    }


    /**
     * 滑动到对应点中部
     *
     * @param recyclerView
     * @param position
     */
    public static void smoothScrollToPositionCenter(RecyclerView recyclerView, int position) {
        new RecyclerViewHelper().attachToRecyclerView(recyclerView).smoothScrollToPositionCenter(position);
    }

    /**
     * 滑动到对应点中部
     */
    static final class RecyclerViewHelper {
        private RecyclerView mRecyclerView;
        @Nullable
        private OrientationHelper mVerticalHelper;
        @Nullable
        private OrientationHelper mHorizontalHelper;

        private final RecyclerView.OnScrollListener mScrollListener = new RecyclerView.OnScrollListener() {
            boolean mScrolled = false;

            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == 0 && this.mScrolled) {
                    this.mScrolled = false;
                }
            }

            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                if (dx != 0 || dy != 0) {
                    this.mScrolled = true;
                }

            }
        };

        public RecyclerViewHelper attachToRecyclerView(@Nullable RecyclerView recyclerView) throws IllegalStateException {
            if (this.mRecyclerView != recyclerView) {
                this.mRecyclerView = recyclerView;
            }
            return this;
        }

        /**
         * 滚动到中间
         *
         * @param position
         */
        public void smoothScrollToPositionCenter(int position) {
            if (this.mRecyclerView != null) {
                RecyclerView.LayoutManager layoutManager = this.mRecyclerView.getLayoutManager();
                if (layoutManager != null) {
                    if (layoutManager instanceof RecyclerView.SmoothScroller.ScrollVectorProvider) {
                        View snapView = this.findSnapView(layoutManager, position);
                        float milliseconds;
                        if (snapView != null) { // 判断
                            milliseconds = 600.0F;
                        } else {
                            milliseconds = 100.0F;
                        }
                        final float finalMilliseconds = milliseconds;
                        RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(this.mRecyclerView.getContext()) {
                            protected void onTargetFound(View targetView, RecyclerView.State state, Action action) {
                                if (mRecyclerView != null) {
                                    int[] snapDistances = calculateDistanceToFinalSnap(mRecyclerView.getLayoutManager(), targetView);
                                    int dx = snapDistances[0];
                                    int dy = snapDistances[1];
                                    int time = this.calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy)));
                                    if (time > 0) {
                                        action.update(dx, dy, time, sInterpolator);
                                    }
                                }
                            }

                            protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                                return finalMilliseconds / (float) displayMetrics.densityDpi;
                            }
                        };

                        smoothScroller.setTargetPosition(position);
                        layoutManager.startSmoothScroll(smoothScroller);
                    }

                }
            }

        }

        /**
         * 插值器
         */
        Interpolator sInterpolator = new Interpolator() {
            public float getInterpolation(float t) {
                t -= 1.0f;
                return t * t * t * t * t + 1.0f;
            }
        };

        int[] calculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, View snapView) {
            int[] out = new int[2];
            if (layoutManager.canScrollHorizontally()) {
                out[0] = this.distanceToCenter(layoutManager, snapView, this.getHorizontalHelper(layoutManager));
            } else {
                out[0] = 0;
            }

            if (layoutManager.canScrollVertically()) {
                out[1] = this.distanceToCenter(layoutManager, snapView, this.getVerticalHelper(layoutManager));
            } else {
                out[1] = 0;
            }

            return out;
        }


        private View findSnapView(RecyclerView.LayoutManager layoutManager, int position) {
            return layoutManager.findViewByPosition(position);
        }

        /**
         * 获取itemview的距离中间的距离
         *
         * @param layoutManager
         * @param targetView
         * @param helper
         * @return
         */
        private int distanceToCenter(@NonNull RecyclerView.LayoutManager layoutManager, @NonNull View targetView, OrientationHelper helper) {
            int childCenter = helper.getDecoratedStart(targetView) + helper.getDecoratedMeasurement(targetView) / 2;
            int containerCenter;
            if (layoutManager.getClipToPadding()) {
                containerCenter = helper.getStartAfterPadding() + helper.getTotalSpace() / 2;
            } else {
                containerCenter = helper.getEnd() / 2;
            }

            return childCenter - containerCenter;
        }

        @NonNull
        private OrientationHelper getVerticalHelper(@NonNull RecyclerView.LayoutManager layoutManager) {
            if (this.mVerticalHelper == null || this.mVerticalHelper.getLayoutManager() != layoutManager) {
                this.mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager);
            }

            return this.mVerticalHelper;
        }

        @NonNull
        private OrientationHelper getHorizontalHelper(@NonNull RecyclerView.LayoutManager layoutManager) {
            if (this.mHorizontalHelper == null || this.mHorizontalHelper.getLayoutManager() != layoutManager) {
                this.mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager);
            }

            return this.mHorizontalHelper;
        }
    }
}
